/**
 * @孙武
 * 自定请求
 */
// const http = 'http://111.231.191.236:8004'
const http="http://127.0.0.1:8004";
const config = {
  domain: http,
  host: http + '/',
  static: http + '/upload/img/',
  app_debug: true
}
import axios from 'axios'
import { Loading } from 'element-ui'
import { Message } from 'element-ui'

axios.interceptors.response.use(function(response) {
  // console.log("resopnse--------------------");
  // console.log(response);
  if (response.data.code === 9) {
    Message({
      type: 'error',
      message: '未授权的操作'
    })
    return 9
  }
  return response
}, function(error) {
  // console.log("error--------------");
  // console.log(error.status);
  return error
})
export default async(url = '', data = null, type = 'sql', method = 'fetch') => {
  type = type.toUpperCase()
  url = config.host + url
  // 将对象解析成get后面？&形式的参数
  if (type === 'GET' || type === 'DOWNLOAD' || type === 'UPLOAD') {
    let dataStr = '' // 数据拼接字符串
    Object.keys(data).forEach(key => {
      // 过滤空字段
      // if (data[key].length > 0 && data[key] !== undefined)
      dataStr += key + '=' + data[key] + '&'
    })
    if (dataStr !== '') {
      dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))
      url = url + '?' + dataStr
    }
  } else if (type === 'RESTFUL') {
    url += data
  } else if (type === 'SQL') {
    console.log(data);
    url += 'sql/' + data
  }
  // 请求服务加载
  const loading = Loading.service({
    fullscreen: true,
    lock: true,
    text: '数据拼命加载中...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.2)',
    customClass: 'loading'

  })

  return new Promise((resolve, reject) => {
    switch (type) {
      case 'UPLOAD': {
        loading.close()
        resolve(url)
      }
        break
      case 'GET': {
        axios.get(url).then(async(res) => {
          loading.close()
          resolve(res.data)
        }).catch(async(err) => {
          loading.close()
          reject(err)
        })
      }
        break
      case 'POST': {
        url = url + '?XDEBUG_SESSION_START=PHPSTORM'
        axios.post(url, data).then(async(res) => {
          loading.close()
          resolve(res.data)
        }).catch(async(err) => {
          loading.close()
          reject(err)
        })
      }
        break
      case 'DOWNLOAD': {
        window.open(url)
        loading.close()
        resolve(url)
      }
        break
      case 'RESTFUL': {
        axios.get(url).then(async(res) => {
          loading.close()
          resolve(res.data)
        }).catch(async(err) => {
          loading.close()
          reject(err)
        })
      } break
      case 'SQL': {
        axios.get(url).then(async(res) => {
          loading.close()
          resolve(res.data)
        }).catch(async(err) => {
          loading.close()
          reject(err)
        })
      } break
    }
  })
}

